<template>
  <div class="inbound-management">
    <!-- 条件查询区域 -->
    <div class="search-section">
      <el-form :model="searchForm" :inline="true" class="search-form">
        <el-form-item label="入库单号">
          <el-input
            v-model="searchForm.inboundCode"
            placeholder="请输入入库单号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        
        
        
        <el-form-item>
          <el-button type="primary" @click="searchData">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="action-section">
      <el-button type="success" @click="openAdd">
        <el-icon><Plus /></el-icon>
        新增入库
      </el-button>
      <el-button type="default" @click="deleteSelected">
        <el-icon><Delete /></el-icon>
        删除
      </el-button>
      <el-button type="default" @click="exportData">
        <el-icon><Download /></el-icon>
        导出
      </el-button>
      <el-button type="default" @click="refreshData">
        <el-icon><Refresh /></el-icon>
        刷新
      </el-button>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <el-table
        :data="inboundData"
        border
        stripe
        style="width: 100%"
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column prop="orderCode" label="入库单号" width="150">
          <template #default="scope">
            <el-link type="primary" @click="viewDetail(scope.row)">
              {{ scope.row.orderCode }}
            </el-link>
          </template>
        </el-table-column>
        
        <el-table-column prop="inboundNum" label="入库数量" width="100" />
       
        <el-table-column prop="goodsName" label="商品名称" width="120" />
        <el-table-column prop="warehouseName" label="入库仓库" width="120" />
        
        <el-table-column prop="inboundTime" label="入库日期" width="160">
          <template #default="scope">
            {{ formatDateTime(scope.row.inboundTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="operator" label="操作人" width="100" />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="editInbound(scope.row)">
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="deleteInbound(scope.row)"
              :disabled="scope.row.status === 'completed'"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    

    <!-- 新增入库 -->
    <el-dialog
      v-model="dialogVisible"
      title="新增入库"
      width="800px"
      
    >        
      <el-form
    ref="ruleFormRef"
    style="max-width: 600px"
    :model="ruleForm"
    :rules="rules"
    label-width="auto"
  >
    <el-form-item label="入库单号" prop="orderCode">
      <el-input v-model="ruleForm.orderCode" readonly placeholder="系统自动生成"disabled/>
    </el-form-item>
    <el-form-item label="仓库名称" prop="warehouseName">
      <el-select v-model="ruleForm.warehouseName" placeholder="请选择仓库">
        <el-option v-for="a in warehouseOptions" :label="a.warehouseName" :value="a.warehouseName" />
        
      </el-select>
    </el-form-item>
    <el-form-item label="商品名称" prop="goodsName">
      <el-select v-model="ruleForm.goodsName" placeholder="请选择商品">
        <el-option v-for="a in goodsOptions" :label="a.goodsName" :value="a.goodsName" />
       
      </el-select>
    </el-form-item>
    <el-form-item label="入库数量" prop="inboundNum">
      <el-input-number v-model="ruleForm.inboundNum" :min="1" :max="99999" placeholder="请输入入库数量" style="width: 100%" />
    </el-form-item>
    <el-form-item label="入库日期" prop="inboundTime">
      <el-date-picker
        v-model="ruleForm.inboundTime"
        type="datetime"
        placeholder="请选择入库日期"
      />
    </el-form-item>
   <el-form-item label="操作人" prop="operator">
      <el-input v-model="ruleForm.operator" />
    </el-form-item>
   
  </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resetForm(ruleFormRef)">取消</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)">确定</el-button>
        </span>
      </template>
    </el-dialog>


    <!-- 修改入库 -->
    <el-dialog
      v-model="updatedialogVisible"
      title="修改入库"
      width="800px"
      
    >        
      <el-form
    ref="updateruleFormRef"
    style="max-width: 600px"
    :model="updateruleForm"
    :rules="updaterules"
    label-width="auto"
  >
    <el-form-item label="入库单号" prop="orderCode">
      <el-input v-model="updateruleForm.orderCode" readonly placeholder="系统自动生成"disabled/>
    </el-form-item>
    <el-form-item label="仓库名称" prop="warehouseName">
      <el-select v-model="updateruleForm.warehouseName" placeholder="请选择仓库">
        <el-option v-for="a in warehouseOptions" :label="a.warehouseName" :value="a.warehouseName" />
        
      </el-select>
    </el-form-item>
    <el-form-item label="商品名称" prop="goodsName">
      <el-select v-model="updateruleForm.goodsName" placeholder="请选择商品">
        <el-option v-for="a in goodsOptions" :label="a.goodsName" :value="a.goodsName" />
       
      </el-select>
    </el-form-item>
    <el-form-item label="入库数量" prop="inboundNum">
      <el-input-number v-model="updateruleForm.inboundNum" :min="1" :max="99999" placeholder="请输入入库数量" style="width: 100%" />
    </el-form-item>
    <el-form-item label="入库日期" prop="inboundTime">
      <el-date-picker
        v-model="updateruleForm.inboundTime"
        type="datetime"
        placeholder="请选择入库日期"
      />
    </el-form-item>
   <el-form-item label="操作人" prop="operator">
      <el-input v-model="updateruleForm.operator" />
    </el-form-item>
   
  </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resetForm(updateruleFormRef)">取消</el-button>
          <el-button type="primary" @click="updateSubmitForm(updateruleFormRef)">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Delete,
  Download,
  Refresh,
  Search
} from '@element-plus/icons-vue'

// 入库数据类型定义
interface InboundItem {
  id: number
  orderCode: string
  goodsName: string
  inboundNum: number
  warehouseName: string
  inboundTime: string
  operator: string
  createTime?: string
  updateTime?: string
}

// 搜索表单
const searchForm = reactive({
  inboundCode: '',
  productName: '',
  status: '',
  dateRange: []
})

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 表格数据
const inboundData = ref<InboundItem[]>([])
const selectedRows = ref<InboundItem[]>([])
const loading = ref(false)

// 对话框相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref()

// 表单数据



// 获取入库数据
const getInboundData =()=> {
    axios.get("http://localhost:5198/api/Inbound/GetInbound").then(res=>{
        inboundData.value = res.data.data
    })
}

// 搜索数据
const searchData = () => {
  pagination.currentPage = 1
  getInboundData()
}

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    inboundCode: '',
    productName: '',
    status: '',
    dateRange: []
  })
  searchData()
}

// 刷新数据
const refreshData = () => {
  getInboundData()
}

// 表格选择变化
const handleSelectionChange = (selection: InboundItem[]) => {
  selectedRows.value = selection
}


// 分页大小变化
const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  getInboundData()
}

// 当前页变化
const handleCurrentChange = (val: number) => {
  pagination.currentPage = val
  getInboundData()
}
//新增
const openAdd=()=>{
    // 生成入库单号：当前时间的年月日时分秒格式
    const now = new Date()
    const year = now.getFullYear()
    const month = String(now.getMonth() + 1).padStart(2, '0')
    const day = String(now.getDate()).padStart(2, '0')
    const hours = String(now.getHours()).padStart(2, '0')
    const minutes = String(now.getMinutes()).padStart(2, '0')
    const seconds = String(now.getSeconds()).padStart(2, '0')
    
    ruleForm.orderCode = `${year}${month}${day}${hours}${minutes}${seconds}`
    dialogVisible.value = true;
}

import type { FormInstance, FormRules } from 'element-plus'
import axios from 'axios'



const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  warehouseName: '',
  orderCode: '',
  goodsName: '',
  inboundNum: 1, // 数字类型，默认值为1
  operator: '',
  inboundTime: '',
  
})

const updateruleFormRef = ref<FormInstance>()
const updaterules = reactive({
  warehouseName: [
    { required: true, message: '仓库名称不能为空', trigger: 'blur' },
  ],
  goodsName: [
    {
      required: true,
      message: '货品名称不能为空',
      trigger: 'change',
    },
  ],
  inboundNum: [
    {
      required: true,
      message: '入库数量不能为空',
      trigger: 'change',
    },
  ],
  operator: [
    {
      required: true,
      message: '经办人不能为空',
      trigger: 'change',
    },
  ],
})

const locationOptions = ['Home', 'Company', 'School']

const rules = reactive({
  warehouseName: [
    { required: true, message: '仓库名称不能为空', trigger: 'blur' },
  ],
  goodsName: [
    {
      required: true,
      message: '货品名称不能为空',
      trigger: 'change',
    },
  ],
  inboundNum: [
    {
      required: true,
      message: '入库数量不能为空',
      trigger: 'change',
    },
  ],
  operator: [
    {
      required: true,
      message: '经办人不能为空',
      trigger: 'change',
    },
  ],
 
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  
  try {
    const valid = await formEl.validate()
    if (valid) {
      // 数据验证
      if (!ruleForm.orderCode) {
        ElMessage.error('入库单号不能为空')
        return
      }
      if (!ruleForm.warehouseName) {
        ElMessage.error('仓库名称不能为空')
        return
      }
      if (!ruleForm.goodsName) {
        ElMessage.error('商品名称不能为空')
        return
      }
      if (!ruleForm.inboundTime) {
        ElMessage.error('入库时间不能为空')
        return
      }
      
      // 格式化日期时间为ISO格式
      const now = new Date()
      const inboundDate = new Date(ruleForm.inboundTime)
      const currentTimeISO = now.toISOString()
      const inboundTimeISO = inboundDate.toISOString()
      
      // 根据后端期望的数据结构构建提交数据
      const submitData = {
        warehouseName: ruleForm.warehouseName,
        orderCode: ruleForm.orderCode,
        goodsName: ruleForm.goodsName,
        inboundNum: Number(ruleForm.inboundNum),
        operator: ruleForm.operator,
        inboundTime: inboundTimeISO,
        createTime: currentTimeISO,
        updateTime: currentTimeISO,
        delTime: currentTimeISO,
        createName: ruleForm.operator, // 使用操作人作为创建人
        updateName: ruleForm.operator, // 使用操作人作为更新人
        delName: "", // 空字符串
        isDeleted: false // 默认为未删除
      }
      
      console.log('原始表单数据:', ruleForm)
      console.log('提交数据:', submitData)
      console.log('数据类型检查:', {
        orderCode: typeof submitData.orderCode,
        warehouseName: typeof submitData.warehouseName,
        goodsName: typeof submitData.goodsName,
        inboundNum: typeof submitData.inboundNum,
        operator: typeof submitData.operator,
        inboundTime: typeof submitData.inboundTime
      })
      
      const response = await axios.post('http://localhost:5230/api/Inbound/AddInbound', submitData)
      
      if (response.data && response.data.code === 200) {
        ElMessage.success('新增入库成功')
        // 清空表单
        ruleForm.goodsName = ''
        ruleForm.warehouseName = ''
        ruleForm.inboundNum = 1 // 数字类型，重置为1
        ruleForm.operator = ''
        ruleForm.inboundTime = ''
        ruleForm.orderCode = ''
        dialogVisible.value = false
        getInboundData()
      } else {
        ElMessage.error(response.data?.message || '新增入库失败')
      }
    }
  } catch (error: any) {
    console.error('提交失败:', error)
    
    if (error.response) {
      // 服务器返回了错误响应
      const status = error.response.status
      const message = error.response.data?.message || error.response.data?.error || '服务器错误'
      
      console.error('服务器错误:', {
        status,
        message,
        data: error.response.data
      })
      
      if (status === 400) {
        ElMessage.error(`请求数据错误: ${message}`)
      } else if (status === 404) {
        ElMessage.error('接口不存在，请检查后端服务')
      } else if (status === 500) {
        console.error('数据库错误详情:', error.response.data)
        if (message.includes('MySql')) {
          ElMessage.error('数据库连接错误，请检查数据库服务是否正常')
        } else {
          ElMessage.error('服务器内部错误，请联系管理员')
        }
      } else {
        ElMessage.error(`请求失败: ${message}`)
      }
    } else if (error.request) {
      // 请求已发送但没有收到响应
      console.error('网络错误:', error.request)
      ElMessage.error('网络连接失败，请检查后端服务是否启动')
    } else {
      // 其他错误
      ElMessage.error('提交失败: ' + error.message)
    }
  }
}

const updateSubmitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid) => {
    if (valid) {
      try {
        // 1. 构建符合API要求的完整payload
        const payload = {
          ...updateruleForm,
          inboundNum: Number(updateruleForm.inboundNum),
          updateName: updateruleForm.operator,
          createName: '',
          delName: '',
          isDelete: false
        };
        const response = await axios.put('http://localhost:5230/api/Inbound/UpdateInbound', payload);

        if (response.data && response.data.code === 200) {
          ElMessage.success('修改入库成功');
          updatedialogVisible.value = false;
          getInboundData(); // 刷新列表
        } else {
          ElMessage.error(response.data.message || '修改失败');
        }
      } catch (error: any) {
        // 4. 统一处理异常
        console.error('修改操作失败:', error);
        const message = error.response?.data?.message || '网络或服务器错误，请稍后重试';
        ElMessage.error(message);
      }
    } else {
      console.log('表单校验失败!');
      ElMessage.error('表单校验失败，请检查输入项');
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

//仓库信息
const warehouseOptions:any = ref([])
const getWarehouseOptions = () => {
  axios.get('http://localhost:5198/api/Warehouse/GetWarehouse').then(res => {
    warehouseOptions.value = res.data.data
  })
}
//商品信息
const goodsOptions:any = ref([])
const getGoodsOptions = () => {
  axios.get('http://localhost:5198/api/StockTaking/GetGoods').then(res => {
    goodsOptions.value = res.data.data
  })
}
const updatedialogVisible=ref(false);
//修改入库
const editInbound = (row: InboundItem) => {
  updatedialogVisible.value = true
  updateruleForm.id = row.id
  updateruleForm.warehouseName = row.warehouseName
  updateruleForm.orderCode = row.orderCode
  updateruleForm.goodsName = row.goodsName
  updateruleForm.inboundNum = row.inboundNum
  updateruleForm.operator = row.operator
  updateruleForm.inboundTime = row.inboundTime
 
}

const updateruleForm = reactive({
   id:0,
  warehouseName: '',
  orderCode: '',
  goodsName: '',
  inboundNum: 1, // 数字类型，默认值为1
  operator: '',
  inboundTime: '',
  
})


// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return ''
  return new Date(dateTime).toLocaleString('zh-CN')
}





// 删除入库
const deleteInbound = async (row: InboundItem) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除入库单号为 "${row.orderCode}" 的记录吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // 根据API文档，删除接口的请求体只需要包含id
    const deletePayload = { id: row.id };
    const response = await axios.put('http://localhost:5230/api/Inbound/DelInbound', deletePayload);

    if (response.data && response.data.code === 200) {
      ElMessage.success('删除成功');
      getInboundData(); // 刷新列表
    } else {
      ElMessage.error(response.data.message || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}
// 批量删除
const deleteSelected = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的记录');
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRows.value.length} 条记录吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    const ids = selectedRows.value.map(row => row.id);
    const response = await axios.delete('http://localhost:5198/api/Inbound/DelInbound', {
      data: ids // 将ID数组作为请求体发送
    });

    if (response.data && response.data.code === 200) {
      ElMessage.success('批量删除成功');
      getInboundData(); // 刷新列表
      selectedRows.value = []; // 清空选择
    } else {
      ElMessage.error(response.data.message || '批量删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error);
      ElMessage.error('批量删除操作失败');
    }
  }
};

// 导出数据
const exportData = () => {
  ElMessage.info('导出功能开发中...')
}

// 查看详情
const viewDetail = (row: InboundItem) => {
  ElMessage.info(`查看入库单号: ${row.orderCode} 的详情`)
}



// 页面加载时获取数据
onMounted(() => {
  getInboundData()
  getWarehouseOptions()
  getGoodsOptions()
})
</script>

<style scoped>
.inbound-management {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.search-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-form {
  margin: 0;
}

.action-section {
  background: white;
  padding: 15px 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.table-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination-section {
  background: white;
  padding: 15px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: center;
}

.dialog-footer {
  text-align: right;
}

.el-button {
  margin-right: 10px;
}

.el-button:last-child {
  margin-right: 0;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-table {
  font-size: 14px;
}

.el-table .el-table__header-wrapper th {
  background-color: #fafafa;
  color: #333;
  font-weight: 600;
}

.el-pagination {
  margin-top: 0;
}

.el-link {
  font-weight: 500;
}

.el-tag {
  font-weight: 500;
}
</style>